/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return merge(lists, 0, lists.length - 1);
    }
    private ListNode merge(ListNode[] lists, int left, int right) {
        if (left == right) {
            return lists[left];
        }
        if (left > right) {
            return null;
        }
        if ((right + left) % 2 == 0) {
            int mid = (right + left) / 2;
            return merge2Lists(merge(lists, left, mid), merge(lists, mid + 1, right));
        } else {
            return merge2Lists(merge(lists, left, right - 1), lists[right]);
        }
    }
    private ListNode merge2Lists(ListNode head1, ListNode head2) {
        if (head1 == head2) {
            return head1;
        }
        ListNode protect = new ListNode();
        ListNode head = protect;
        while (head1 != null && head2 != null) {
            if (head1.val <= head2.val) {
                head.next = head1;
                head1 = head1.next;
            } else {
                head.next = head2;
                head2 = head2.next;
            }
            head = head.next;
        }
        if (head1 != null) {
            head.next = head1;
        }
        if (head2 != null) {
            head.next = head2;
        }
        return protect.next;
    }
}
